<template>
	<view class="container">
		<Navigator2 :title="$t('me.editNickname')"></Navigator2>
		<view class="content">
			<input 
				class="nickname-input" 
				v-model="username" 
				:placeholder="$t('me.editNicknamePlaceholder')" 
				maxlength="20"
				:focus="true"
			/>
			<view class="confirm-button-container">
				<button class="confirm-button" @click="confirmEdit">{{ $t('me.confirmEdit') }}</button>	
			</view>
		</view>
	</view>
</template>

<script>
	import Navigator2 from '@/components/Navigator2.vue'
	import api from '@/js/api.js'
	export default {
		data() {
			return {
				username: uni.getStorageSync('userInfo').username
			}
		},
		methods: {
			confirmEdit() {
				if (!this.username.trim()) {
					uni.showToast({
						title: this.$t('me.editNicknamePlaceholder'),
						icon: 'none'
					})
					return
				}
				
				const userInfo = uni.getStorageSync('userInfo')
				api.editNickname(userInfo.phone, this.username).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: this.$t('me.editNicknameSuccess'),
							icon: 'success'
						})
						uni.setStorageSync('userInfo', {
							...userInfo,
							username: this.username
						})
					} else {
						uni.showToast({
							title: this.$t('me.editNicknameFail'),
							icon: 'none'
						})
					}
				})
				
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					})
				}, 1500)
			}
		},
		components: {
			Navigator2
		}
	}
</script>

<style lang="scss">
/* 全局样式 */
page {
	background-color: #F1F2F5;
}
</style>

<style lang="scss" scoped>
	.container {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100vh;
		background-color: #F1F2F5;
		overflow: hidden;
		
		.content {
			display: flex;
			flex-direction: column;
			height: calc(100vh - 100px);
			position: relative;
			border-top: 1px solid #F0F2F5;
			
			.nickname-input {
				background-color: #FFFFFF;
				border: none;
				outline: none;
				padding: 20px 16px;
				font-size: 16px;
				color: #1F2937;
				width: 100%;
				height: 60px;
				box-sizing: border-box;
				display: block;
				
				&::placeholder {
					color: #C0C4CC;
					font-size: 16px;
				}
			}
			
			.confirm-button-container {
				position: fixed;
				bottom: 0;
				left: 0;
				right: 0;
				z-index: 100;
				background-color: #FFFFFF;
				padding: 16px;
				box-sizing: border-box;

				.confirm-button {
					background-color: #0256FF;
					color: #FFFFFF;
					border: none;
					border-radius: 8px;
					padding: 8px 16px;
					font-size: 16px;
					width: 100%;
					
					&:active {
						background-color: #0051D5;
					}
				}
			}
			
		}
	}
</style>
